package com.sh.filter;

import com.sh.util.JwtUtils;
import com.sh.util.RedisConstant;
import com.sh.util.SystemConstant;
import com.sh.wy.system.entity.LiveUser;
import com.sh.wy.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 世豪学java
 * @Date: 2023/12/17 - 12 - 17 - 13:43
 * @Decsription: com.sh.filter
 * @version: 1.0
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求头中获取token
        String token = request.getHeader("authorization");
        /*Strings.isBlank()*/
        /*!StringUtils.hasText(token)*/
        /*Objects.isNull()*/
        if (!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            //防止返回时再执行一次
            return;
        }

        //解析token
        Integer userId;
        Integer userType;

        try {
            userId = jwtUtils.getUserIdFromToken(token);
            userType = jwtUtils.getUserTypeFromToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        //刷新token和redis有效期
        //刷新token
        //直接粘贴
        String refreshToken = jwtUtils.refreshToken(token);
        response.setHeader("Access-Control-Expose-Headers","Authorization");
        response.addHeader("Authorization",refreshToken);

        //从token中获取信息
        if (SystemConstant.USER_TYPE_WUZHU == userType){
            SysUser sysUser =(SysUser) redisTemplate.opsForValue().get(RedisConstant.LOGIN_SYSTEM_USER_PRE + userId);
            if (Objects.isNull(sysUser)){
                throw new RuntimeException("用户未登录");
            }
            //刷新redis缓存
            redisTemplate.expire(RedisConstant.LOGIN_SYSTEM_USER_PRE + userId,RedisConstant.LOGIN_SYSTEM_USER_EXPIRE_TIME, TimeUnit.MINUTES);

            //保存用户信息
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                    //设置权限
                    = new UsernamePasswordAuthenticationToken(sysUser,null,sysUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            //放行
            filterChain.doFilter(request,response);
        }else {
            LiveUser liveUser =(LiveUser) redisTemplate.opsForValue().get(RedisConstant.LOGIN_LIVE_USER_PRE + userId);
            if (Objects.isNull(liveUser)){
                throw new RuntimeException("用户未登录");
            }
            //刷新redis缓存
            redisTemplate.expire(RedisConstant.LOGIN_LIVE_USER_PRE + userId,RedisConstant.LOGIN_LIVE_USER_EXPIRE_TIME, TimeUnit.MINUTES);

            //保存用户信息
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                    //设置权限
                    = new UsernamePasswordAuthenticationToken(liveUser,null,liveUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            //放行
            filterChain.doFilter(request,response);
        }
    }
}
